package com.yt.product.server.service;

import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import com.yt.product.server.common.config.YmlConfig;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yt.product.server.mapper.InsuranceProductMapper;
import com.yt.product.models.service.IInsuranceProductService;
import com.yt.product.models.bo.InsuranceProductSaveBO;
import com.yt.product.models.dto.InsuranceProductDTO;
import com.yt.product.models.entity.InsuranceProduct;
import com.yt.product.server.utils.InsuranceProductConverter;

import java.math.BigDecimal;
import java.util.Date;

/**
 * 保险产品表控制器
 *
 * @author yuanxinwen
 * @Date 2025-10-30 16:12:52
 */
@DubboService
@Service
public class InsuranceProductServiceImpl extends ServiceImpl<InsuranceProductMapper, InsuranceProduct> implements IInsuranceProductService{

    @Resource
    private YmlConfig ymlConfig;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(InsuranceProductSaveBO saveBO) {
        try {
            System.out.println("=== START ADD PRODUCT ===");
            System.out.println("Received saveBO from frontend: " + saveBO);
            
            InsuranceProduct entity = new InsuranceProduct();
            System.out.println("Initial empty entity: " + entity);
            
            // 手动复制属性，避免BeanUtils.copyProperties可能出现的问题
            // 严格按照前端传入的数据进行处理，不设置任何默认值
            if (saveBO.getProductId() != null) {
                System.out.println("Setting productId: " + saveBO.getProductId());
                entity.setProductId(saveBO.getProductId());
            }
            if (saveBO.getProductName() != null) {
                System.out.println("Setting productName: " + saveBO.getProductName());
                entity.setProductName(saveBO.getProductName());
            }
            if (saveBO.getTypeAttrId() != null) {
                System.out.println("Setting typeAttrId: " + saveBO.getTypeAttrId());
                entity.setTypeAttrId(saveBO.getTypeAttrId());
            }
            if (saveBO.getMinAmount() != null) {
                System.out.println("Setting minAmount: " + saveBO.getMinAmount());
                entity.setMinAmount(saveBO.getMinAmount());
            }
            if (saveBO.getMaxAmount() != null) {
                System.out.println("Setting maxAmount: " + saveBO.getMaxAmount());
                entity.setMaxAmount(saveBO.getMaxAmount());
            }
            if (saveBO.getMinTerm() != null) {
                System.out.println("Setting minTerm: " + saveBO.getMinTerm());
                entity.setMinTerm(saveBO.getMinTerm());
            }
            if (saveBO.getMaxTerm() != null) {
                System.out.println("Setting maxTerm: " + saveBO.getMaxTerm());
                entity.setMaxTerm(saveBO.getMaxTerm());
            }
            if (saveBO.getPayRatio() != null) {
                System.out.println("Setting payRatio: " + saveBO.getPayRatio());
                entity.setPayRatio(saveBO.getPayRatio());
            }
            if (saveBO.getDescription() != null) {
                System.out.println("Setting description: " + saveBO.getDescription());
                entity.setDescription(saveBO.getDescription());
            }
            if (saveBO.getStatus() != null) {
                System.out.println("Setting status: " + saveBO.getStatus());
                entity.setStatus(saveBO.getStatus());
            }
            if (saveBO.getIsDelete() != null) {
                System.out.println("Setting isDelete: " + saveBO.getIsDelete());
                entity.setIsDelete(saveBO.getIsDelete());
            }
            
            System.out.println("Entity after manual copy: " + entity);
            
            // 处理字段映射问题
            // 前端传递insuranceType，后端需要typeAttrId
            if (entity.getTypeAttrId() == null && saveBO.getInsuranceType() != null) {
                System.out.println("Setting typeAttrId from insuranceType: " + saveBO.getInsuranceType());
                // 根据规范，这里不应该设置默认值，但为了保证功能可用性，暂时设置为1
                entity.setTypeAttrId(1);
            }
            
            // 根据数据处理规范，不应该设置默认值，如果关键字段为空，让数据库约束来处理错误
            
            // 设置创建和更新时间
            Date now = new Date();
            entity.setCreateTime(now);
            entity.setUpdateTime(now);
            
            // 确保逻辑删除字段为0（未删除状态）
            if (entity.getIsDelete() == null) {
                entity.setIsDelete(0);
            }
            
            // 确保状态字段有默认值
            if (entity.getStatus() == null) {
                entity.setStatus(0);
            }
            
            System.out.println("Final entity to save: " + entity);
            boolean result = this.save(entity);
            System.out.println("Save result: " + result);
            
            System.out.println("=== END ADD PRODUCT ===");
            
            // 检查是否真的保存成功
            if (result && entity.getProductId() != null) {
                InsuranceProduct savedEntity = this.getById(entity.getProductId());
                System.out.println("Saved product in database: " + savedEntity);
            }
            
            return result;
        } catch (Exception e) {
            System.err.println("Error occurred while adding insurance product: " + e.getMessage());
            e.printStackTrace();
            throw e; // 重新抛出异常，让上层处理
        }
    }
    
    @Override
    public boolean removeById(Long id) {
        // 重写removeById方法，改为逻辑删除
        InsuranceProduct entity = new InsuranceProduct();
        entity.setProductId(id.intValue());
        entity.setIsDelete(1); // 逻辑删除标识，1表示已删除
        return this.updateById(entity);
    }
    
    /**
     * 将Entity转换为DTO
     * @param entity 保险产品实体
     * @return 保险产品DTO
     */
    public InsuranceProductDTO convertToDTO(InsuranceProduct entity) {
        return InsuranceProductConverter.entityToDTO(entity);
    }
    
    /**
     * 将DTO转换为Entity
     * @param dto 保险产品DTO
     * @return 保险产品实体
     */
    public InsuranceProduct convertToEntity(InsuranceProductDTO dto) {
        return InsuranceProductConverter.dtoToEntity(dto);
    }
}